package com.gexin.service.freeacquire;

import com.alibaba.fastjson.JSONObject;
//import com.gexin.controller.commom.WeixinTransfer.WeixinTransferUtil;
import com.gexin.controller.commom.WeixinTransfer.WeixinTransferUtil;
import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferResult;
import com.gexin.model.activity.Activity;
import com.gexin.model.activity.Cashback;
import com.gexin.model.activity.CashbackBalanceNum;
import com.gexin.model.activity.FreeAcquire;
import com.gexin.model.activity.base.CashbackComparaotor;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentProductSku;
import com.gexin.model.order.OrderItem;
import com.gexin.model.product.Products;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.jfinal.kit.Ret.fail;

public class FreeAcquireService {
    public static final FreeAcquire freeAcquire = new FreeAcquire();

    /**
     * 查找所有页面数据
     * @param page
     * @param pageSize
     * @return
     */
    public static Page<FreeAcquire> findList(int page, int pageSize) {

        return FreeAcquire.dao.findActivityByTime(page,pageSize);
     }

    public FreeAcquire freeAcquire(){
        return FreeAcquire.dao.findFreeAcquireByTime();
    }

    /**
     * 插入新品
     * @param activity
     * @param freeAcquire
     */
    @Before(Tx.class)
    public void insertFreeAcquire(Activity activity,FreeAcquire freeAcquire){
        String activityUuid = UUID.randomUUID().toString();
        activity.setId(activityUuid);
        activity.setCreateTime(new Date());
        activity.save();

        freeAcquire.setId(UUID.randomUUID().toString());
        freeAcquire.setActivityId(activityUuid);
        freeAcquire.setCreateTime(new Date());
        freeAcquire.save();

    }


    public List findCheckProduct() {
        List<Products> allProductList = Products.dao.getAllProducts();
        List<FreeAcquire> checkPoductList = freeAcquire.dao.getAllCheckProduct();
        List list = new ArrayList();
        for(Products product:allProductList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("label",product.getProductName());
            Integer id = product.getId();
            jsonObject.put("id",id);
            list.add(jsonObject);
            for(FreeAcquire freeAcquire:checkPoductList){
                String productId = freeAcquire.getProductId();
                if(StringUtils.isNotBlank(productId)&&String.valueOf(id).equals(productId)){
                    jsonObject.put("checked",true);
                }
            }

        }
        return list;
    }

    @Before(Tx.class)
    public Boolean addProductWithFreeAcquire(String productId,String acitivityId) {
        FreeAcquire freeAcquire = new FreeAcquire();
        Products products = new Products();
        Products byId = products.findById(productId);
        if(null==byId){
            return null;
        }
        freeAcquire.setId(UUID.randomUUID().toString());
        freeAcquire.setProductId(productId);
        freeAcquire.setActivityId(acitivityId);
        freeAcquire.setCreateTime(new Date());
        freeAcquire.save();

        Page<Agent> agentPage = Agent.dao.findAgentList(1, 100, null, null, "0");
        List list = agentPage.getList();
        for(int i=0;i<list.size();i++){
            Agent agent = (Agent) list.get(i);
            AgentProductSku agentProductSku = new AgentProductSku();
            agentProductSku.setId(UUID.randomUUID().toString());
            agentProductSku.setAgentId(agent.getId()+"");
            agentProductSku.setStockNum(0);
            agentProductSku.setSaleNum(0);
            agentProductSku.setProductId(freeAcquire.getProductId());
            agentProductSku.save();
        }
        return true;
    }

    public static  final Integer  EXAMINATION_SEND = 0;

    @Before(Tx.class)
    public void queryFreeacquireList(){
//          先order_item查找范围内的订单,根据id去cashback表查找相关的返现金额,加在一起,如果金额和等于order_item的总价格
            List<CashbackBalanceNum>  cashbackBalanceNumRuleList = CashbackBalanceNum.dao.findAll();
            List<OrderItem> orderItemList = OrderItem.dao.getOrderItemsByProductIdAndFreeAcquire();
            for(int j=0;j<orderItemList.size();j++){
                OrderItem orderItem = orderItemList.get(j);
                Integer itemId = orderItem.get("item_id");
                if(null==itemId) {
                    continue;
                }
                BigDecimal unitPrice = orderItem.get("unit_price");

//              检索所有cashback表中所有的某个itemid的产品
                final BigDecimal[] cashbackBalanceSum = {new BigDecimal("0.00")};
                List<Cashback> cashbackList = Cashback.dao.findCashbackListByItemId(""+itemId);
                cashbackList.forEach(cashback -> {
                    BigDecimal cashbackBalance = cashback.getCashbackBalance();
                    if(null==cashbackBalance)cashbackBalance = new BigDecimal("0.00");
                    cashbackBalanceSum[0] = cashbackBalanceSum[0].add(cashbackBalance);
                });
                if(cashbackBalanceSum[0].compareTo(unitPrice)>-1){
                    continue;
                }


//              本次item要添加的返现金额
                AtomicReference<BigDecimal> currentAddCashbackBalance = new AtomicReference<BigDecimal>();
                currentAddCashbackBalance.set(new BigDecimal("0.00"));
                AtomicReference<Boolean> flag = new AtomicReference<>(false);
                cashbackBalanceNumRuleList.forEach(cashbackBalanceNumRule -> {
                    Date itemCreateTime = orderItem.get("createtime");
                    if(null==cashbackBalanceNumRule.getOperationStartTime())
                        cashbackBalanceNumRule.setOperationStartTime(new Date());
                    if(null==cashbackBalanceNumRule.getOperationEndTime())
                        cashbackBalanceNumRule.setOperationStartTime(new Date());
                    if(itemCreateTime.after(cashbackBalanceNumRule.getOperationStartTime())&&
                            itemCreateTime.before(cashbackBalanceNumRule.getOperationEndTime())
                            &&(orderItem.getProductId()+"").equals(cashbackBalanceNumRule.getProductId())) {
                        flag.set(true);
                        BigDecimal currentCashbackBalance = cashbackBalanceNumRule.getCashbackBalance();
                        if (null == currentCashbackBalance)
                            currentCashbackBalance = new BigDecimal("0.00");
                        currentAddCashbackBalance.set(currentCashbackBalance);
                    }
                });
                if(!flag.get()){
                    continue;
                }
//                CashbackComparaotor cashbackComparaotor = new CashbackComparaotor();
//                if(cashbackList.size()>0){
//                    Cashback maxCashback = Collections.max(cashbackList, cashbackComparaotor);
//                    if(maxCashback.getCashbackBalanceSum().compareTo(unitPrice)>1){
//                        continue;
//                    }
//                }
                Cashback cashback = new Cashback();
                String id = UUID.randomUUID().toString();
                BigDecimal currentBalanceSum = cashbackBalanceSum[0].add(currentAddCashbackBalance.get());
                if(currentBalanceSum.compareTo(unitPrice)>1){
                    BigDecimal leftoverBalance = unitPrice.subtract(currentBalanceSum);
                    cashback.setItemIdAndBalanceAndSum(id,itemId+"",leftoverBalance,currentBalanceSum,new Date());
                }
                if(cashbackBalanceSum[0].compareTo(unitPrice)<0){
                    cashback.setItemIdAndBalanceAndSum(id,itemId+"",currentAddCashbackBalance.get(),currentBalanceSum,new Date());
                }
                accountCashback();
                cashback.save();
            }
    }



    public void accountCashback(){
        WeixinUser authUser = new WeixinUser();
        UserRebate userRebate = new UserRebate();
        WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
        WeixinTransferResult transfer = WeixinTransferUtil.transfer(
                weixinAppConfig.getAppId(),
                weixinAppConfig.getWxKey(),
                weixinAppConfig.getWxMchid(),
                weixinAppConfig.getKeystoreFilePath(),
                authUser.getOpenid(),
                userRebate.getId(),
                authUser.getNickname(),
                userRebate.getPrice(),
                "商品返现");

    }

    public String cashbackList(String productId,Boolean isUserId){
        List<OrderItem> orderItemList = OrderItem.dao.getOrderItemsByProductIdAndFreeAcquire();
        if(isUserId){
            List<WeixinUser> weixinUserByIdList = WeixinUser.dao.findAll();
            orderItemList.stream().forEach(orderItem -> {
                Integer userId = orderItem.get("user_id");
                    weixinUserByIdList.stream().forEach(weixinUser -> {
                        if(null!=userId) {
                            WeixinUser userById = weixinUser.getUserById(userId);
                            if (null != userById) {
                                String username = userById.getNickname();
                                orderItem.put("username", username);
                            }
                        }
                    });
            });
        }
        Map<Integer, List<OrderItem>> groupByCategoryIdAfterMap =  orderItemList
                .stream()
                .collect(Collectors.groupingBy(orderItem->orderItem.get("user_id")));
        return null;
    }

}
